/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package components;

import dao.VeterinarianDAO;
import entity.Appointment;
import entity.Veterinarian;
import hpvas.HPVAS;
import java.text.SimpleDateFormat;
import java.util.List;
import javax.persistence.Persistence;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Juan
 */
public class PVetDisplay extends javax.swing.JPanel {
    
    private boolean changes = false;
    private Veterinarian currentVeterinarian = null;
    private List<Appointment> currentAppointments;

    /**
     * Creates new form POwnerRegistration
     */
    public PVetDisplay() {
        initComponents();
        initialize();
    }
    
    public PVetDisplay(Veterinarian veterinarian) {
        initComponents();
        initialize();
        this.currentVeterinarian = veterinarian;
        LVetName.setText(veterinarian.getName() + "  " + veterinarian.getLastname());
        LSSN.setText(veterinarian.getSSN());
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
        LBirthday.setText(dateFormat.format(veterinarian.getBirthday()));
        LBirthplace.setText(veterinarian.getBirthplace());
        LFocusOfPractice.setText(veterinarian.getFocusOfPractice());
        LSpecialities.setText(veterinarian.getSpecialities());
        LSalary.setText(String.valueOf(veterinarian.getSalary()));
        LGraduatedAt.setText(veterinarian.getGraduatedAt());
        
        currentAppointments = veterinarian.getAppointments();
        DefaultTableModel model = (DefaultTableModel) TAppointments.getModel();
        for (Appointment appointment : currentAppointments) {
            addAppointmentToTable(appointment, model);
        }
    }
    
    private void addAppointmentToTable(Appointment appointment, DefaultTableModel model) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
        model.addRow(new Object[] {appointment.getMedicalRecord().getPet(),
                                       dateFormat.format(appointment.getAppointmentDate()),
                                       appointment.getCharge(),
                                       appointment.getNotes()});
    }
    
    private void initialize() {
        TAppointments.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

            @Override
            public void valueChanged(ListSelectionEvent e) {
                int firstIndex = e.getFirstIndex();
                if (firstIndex != -1) {
                    BDeleteAppointment.setEnabled(true);
                } else {
                    BDeleteAppointment.setEnabled(false);
                }
            }
        });
    }
    
    public void save() {
        if (changes) {
            VeterinarianDAO veterinarianDAO = new VeterinarianDAO(Persistence.createEntityManagerFactory("HPVA"));
            currentVeterinarian.setAppointments(currentAppointments);
            try {
                veterinarianDAO.edit(currentVeterinarian);
                HPVAS.loadOwners();
                HPVAS.loadPets();
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this.getTopLevelAncestor(),
                        "There was an error saving the appointments.", "Error", JOptionPane.ERROR_MESSAGE);
                System.err.println(ex.getMessage());
            }
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        LVetName = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        BClose = new javax.swing.JButton();
        BEdit = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        LSSN = new javax.swing.JLabel();
        LBirthday = new javax.swing.JLabel();
        LBirthplace = new javax.swing.JLabel();
        LFocusOfPractice = new javax.swing.JLabel();
        LSpecialities = new javax.swing.JLabel();
        LSalary = new javax.swing.JLabel();
        LGraduatedAt = new javax.swing.JLabel();
        BDelete = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        TAppointments = new javax.swing.JTable();
        BAddAppointment = new javax.swing.JButton();
        BDeleteAppointment = new javax.swing.JButton();

        LVetName.setText("Vet Name:");

        jLabel4.setText("SSN:");

        jLabel5.setText("Birthday:");

        jLabel6.setText("Birthplace:");

        BClose.setText("Close");
        BClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BCloseActionPerformed(evt);
            }
        });

        BEdit.setText("Edit Veterinarian");
        BEdit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BEditActionPerformed(evt);
            }
        });

        jLabel7.setText("Focus of Practice:");

        jLabel8.setText("Specialities:");

        jLabel9.setText("Salary:");

        jLabel10.setText("US$");

        jLabel11.setText("Graduated At:");

        LSSN.setText("SSn");

        LBirthday.setText("jLabel1");

        LBirthplace.setText("jLabel1");

        LFocusOfPractice.setText("Foc");

        LSpecialities.setText("jLabel1");

        LSalary.setText("jLabel1");

        LGraduatedAt.setText("jLabel1");

        BDelete.setText("Delete Veterinarian");
        BDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BDeleteActionPerformed(evt);
            }
        });

        jLabel2.setText("Appointments:");

        TAppointments.setAutoCreateRowSorter(true);
        TAppointments.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Pet", "Date", "Charge", "Notes"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.Object.class, java.lang.Integer.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        TAppointments.getTableHeader().setReorderingAllowed(false);
        jScrollPane2.setViewportView(TAppointments);

        BAddAppointment.setText("Add Appointment");
        BAddAppointment.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BAddAppointmentActionPerformed(evt);
            }
        });

        BDeleteAppointment.setText("Delete Appointment");
        BDeleteAppointment.setEnabled(false);
        BDeleteAppointment.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BDeleteAppointmentActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(LVetName)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel4)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(LSSN))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel5)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(LBirthday))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel6)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(LBirthplace))
                            .addComponent(jLabel7)
                            .addComponent(jLabel8)
                            .addComponent(jLabel9)
                            .addComponent(jLabel11)
                            .addComponent(LFocusOfPractice)
                            .addComponent(LSpecialities)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel10)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(LSalary))
                            .addComponent(LGraduatedAt)
                            .addComponent(jLabel2)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(BClose)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(BEdit)
                                .addGap(18, 18, 18)
                                .addComponent(BDelete))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(BAddAppointment)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(BDeleteAppointment)))
                        .addGap(0, 83, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(LVetName)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(LSSN))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(LBirthday))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(LBirthplace)
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel7)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(LFocusOfPractice)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel8)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(LSpecialities)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel9)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel10)
                    .addComponent(LSalary))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel11)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(LGraduatedAt)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(BAddAppointment)
                    .addComponent(BDeleteAppointment))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(BClose)
                    .addComponent(BEdit)
                    .addComponent(BDelete))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void BEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BEditActionPerformed
        save();
        HPVAS.editEntity(currentVeterinarian);
    }//GEN-LAST:event_BEditActionPerformed

    private void BCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BCloseActionPerformed
        save();
        HPVAS.closeCurrentTab();
    }//GEN-LAST:event_BCloseActionPerformed

    private void BDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BDeleteActionPerformed
        save();
        HPVAS.deleteEntity(currentVeterinarian);
    }//GEN-LAST:event_BDeleteActionPerformed

    private void BDeleteAppointmentActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BDeleteAppointmentActionPerformed
        int selectedRow = TAppointments.convertRowIndexToModel(TAppointments.getSelectedRow());
        System.out.println(selectedRow + " SR");
        if (selectedRow != -1) {
            DefaultTableModel model = (DefaultTableModel) TAppointments.getModel();
            model.removeRow(selectedRow);
            currentAppointments.remove(selectedRow);
            changes = true;
            TAppointments.getSelectionModel().setSelectionInterval(selectedRow - 1, selectedRow - 1);
        }
        if (selectedRow - 1 == -1) {
            BDeleteAppointment.setEnabled(false);
        }
    }//GEN-LAST:event_BDeleteAppointmentActionPerformed

    private void BAddAppointmentActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BAddAppointmentActionPerformed
        Appointment newAppointment = ComponentFactory.newAppointmentDialog((JFrame) this.getTopLevelAncestor());
        if (newAppointment != null) {
            newAppointment.setVeterinarian(currentVeterinarian);
            currentAppointments.add(newAppointment);
            addAppointmentToTable(newAppointment, (DefaultTableModel) TAppointments.getModel());
            changes = true;
        }
    }//GEN-LAST:event_BAddAppointmentActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton BAddAppointment;
    private javax.swing.JButton BClose;
    private javax.swing.JButton BDelete;
    private javax.swing.JButton BDeleteAppointment;
    private javax.swing.JButton BEdit;
    private javax.swing.JLabel LBirthday;
    private javax.swing.JLabel LBirthplace;
    private javax.swing.JLabel LFocusOfPractice;
    private javax.swing.JLabel LGraduatedAt;
    private javax.swing.JLabel LSSN;
    private javax.swing.JLabel LSalary;
    private javax.swing.JLabel LSpecialities;
    private javax.swing.JLabel LVetName;
    private javax.swing.JTable TAppointments;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane2;
    // End of variables declaration//GEN-END:variables
}
